import axios from 'axios';
import {Message} from 'element-ui';
import store from '@/store';
import {getToken, setToken} from '@/utils/auth';
import {baseUrl, timeOut} from '@/api/constant';

// create an axios instance
const service = axios.create({
  baseURL: baseUrl,
  // baseURL: process.env.BASE_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: timeOut // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is send
    if (store.getters.token) {
      // ['X-Token'] is a custom headers key
      config.headers['tk'] = getToken();
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const result = response.data;

    if (result.code !== 0) {//请求失败
      if (result.code === 10002) {
        Message({
          message: `登录失效,请重新登录[${result.code}]`,
          duration: 2000,
          onClose: () => {
            store.dispatch('user/logout').then(() => {
              location.reload()
            })
          }
        });
      } else if(result.code === 10006){
        store.dispatch('user/logout').then(() => {
          location.reload()
        })
      } else {
        Message({
          message: `${result.msg}[${result.code}]` || 'Error',
          type: 'error',
          duration: 2 * 1000
        });
      }
      return Promise.reject(new Error(result.msg || 'Error'))
    } else {
      if (response.headers && response.headers['tk']) {
        const token = response.headers['tk'];
        setToken(token);
      }
      return result;
    }
  },
  error => {//服务宕机
    Message({
      message: error.message,
      type: 'error',
      duration: 2 * 1000
    });
    return Promise.reject(error)
  }
);

export default service
